import React, { Component } from 'react'
import {
  Layout,
  Input,
  Row,
  Menu,
  Breadcrumb,
  Select,
  Button,
  Dropdown,
  Pagination,
  Tooltip,
  Tabs,
  DatePicker,
  ConfigProvider,
  Modal,
  Spin,
  message,
  Form,
  Popconfirm,
} from 'antd'
import zhCN from 'antd/es/locale/zh_CN'
import 'moment/locale/zh-cn'
import { withRouter } from 'react-router-dom'
import {
  uncompileStr,
  VerifySessionTime,
  getHeaderParams,
  compileStrCop,
  compileStr,
  queryAuth,
  getResponseUrl,
  getLinkToUrl,
  devProTest,
  findConfig,
  frontUrlTest,
  getAjaxurl,
} from '../../rudexRou/OperatesCookie.js'
import { dataAxios } from '../../rudexRou/request.js'
import moment from 'moment'
import axios from '../../rudexRou/urlHttp.js'
import { DownOutlined } from '@ant-design/icons'
const { Header, Footer, Content, Sider } = Layout
const { Option } = Select
const { TabPane } = Tabs
const { MonthPicker } = DatePicker
const { TextArea } = Input
const { SubMenu } = Menu
class HeaderMenu extends Component {
  constructor(props) {
    super(props)
    this.state = {
      MenuData: [],
      JudgeWhetherOrNotShowTable: [],
      Breadcrumb: [],
      roleName:
        this.props.roleList && this.props.roleList.length > 0
          ? this.props.roleList[0].roleName
          : '默认角色',
      roleList:
        this.props.roleList && this.props.roleList.length > 0
          ? this.props.roleList
          : [],
    }
  }
  componentDidMount() {
    // let data = JSON.parse(localStorage.getItem("config"))
    // if (!data) {
    //     this.props.setIsMenus()
    //     this.getMenus()
    // } else {
    //     this.getMenusBylocalStorage()
    // }
    this.getMenusBylocalStorage()
    this.GetUserInfo()
  }
  componentWillReceiveProps(nextProps) {
    let data = JSON.parse(localStorage.getItem('config'))
    let pathObj = getHeaderParams()
    this.getBreadcrumb(data, pathObj.menuId)
  }
  componentWillUnmount() {
    this.setState = (state, callback) => {
      return
    }
  }
  toLinkICan() {
    if (
      '10019045' === JSON.parse(localStorage.getItem('userInfo')).hrBgno ||
      '10039899' === JSON.parse(localStorage.getItem('userInfo')).hrBgno ||
      '10039900' === JSON.parse(localStorage.getItem('userInfo')).hrBgno
    ) {
      window.location.href =
        getLinkToUrl('Home') + '/IndexPagesComponentMainPage'
    } else {
      window.location.href =
        getLinkToUrl('Home') + '/IndexUserPagesComponentMainPage'
    }
  }
  //获取面包屑
  getBreadcrumb(data, id) {
    let _this = this,
      list = []

    data.map((item) => {
      // if (item.systemId == id) {
      //     list.push(item)
      // } else {
      //     item.services.map(its => _this.searchChildid(list, [item], its, id))
      // }
      //为了防止systemId与menuId 出现相同情况。所以暂不考虑systemId那一层，从属性services层开始循环
      item.services.map((its) => _this.searchChildid(list, [item], its, id))
    })
    this.setState({ Breadcrumb: list })
  }
  searchChildid(list, parentlist, its, id) {
    let _this = this
    if (its.type != 2) {
      // debugger
      if (its.menuId == id) {
        parentlist.push(its)
        parentlist.map((it) => list.push(it))
      } else {
        let arry = [...parentlist]
        arry.push(its)
        its.sonMenus &&
          its.sonMenus.map((it) => _this.searchChildid(list, arry, it, id))
      }
    }
  }
  //通过从localStorage中获取
  getMenusBylocalStorage = () => {
    let data = JSON.parse(localStorage.getItem('config'))
    let arry = [...data]
    //单独处理系统配置
    arry.map((item, index) => {
      if (item.systemId === 5) {
        //系统配置菜单特殊处理
        arry.splice(index, 1)
      }
    })
    let isOpenzone = false //黄区
    isOpenzone = uncompileStr(localStorage.getItem('subarea'))
    let pathObj = getHeaderParams()
    this.getBreadcrumb(data, pathObj.menuId)
    if (isOpenzone == 'true') {
      //绿区
      if (data != null) {
        data.map((item, index) => {
          if (item.systemId === 5) {
            if (
              item.services.length === 1 &&
              item.services[0].routeId === 'mag-its-upload-project'
            ) {
              //待办任务菜单特殊处理
              data.splice(index, 1)
            } else {
              if (item.services.length > 1) {
                item.services.map((children, num) => {
                  if (children.routeId === 'mag-its-upload-project') {
                    //待办任务菜单处理
                    item.services.splice(num, 1)
                  }
                  if (
                    children.routeId === 'mag-its-release-project' &&
                    children.sonMenus.length > 0
                  ) {
                    //巡检专员菜单单独处理
                    children.sonMenus.map((res, p) => {
                      if (res.menuId === 147) {
                        children.sonMenus.splice(p, 1)
                      }
                    })
                  }
                })
              }
            }
          }
        })
        this.setState(
          {
            MenuData: data,
          },
          () => {
            this.setHeaderStyle()
          }
        )
      }
    } else {
      this.setState(
        {
          MenuData: arry,
        },
        () => {
          this.setHeaderStyle()
        }
      )
    }
  }
  // //通过接口获取菜单
  // getMenus() {
  //     dataAxios({
  //         url: '/auth/queryMenusByToken',
  //         type: "get",
  //     }).then((response) => {
  //         if (response.status === 200) {
  //             if (response.data.code === 200 && response.data.message == "OK") {
  //                 this.getUserOperatorInfo();
  //                 this.props.setIsMenus()
  //                 localStorage.setItem("config", JSON.stringify(response.data.data))
  //                 this.getMenusBylocalStorage()
  //             }
  //         }
  //     }).catch((error) => {
  //         console.log(error)
  //     });
  // }
  getUserOperatorInfo(data) {
    let _this = this
    dataAxios({
      url: 'release/config/getUserOperatorInfo',
      params: {},
    })
      .then((response) => {
        if (response.status === 200 && response.data.code === 200) {
          localStorage.setItem(
            'userInfoOpreate',
            JSON.stringify(response.data.data)
          )
        }
      })
      .catch((err) => {
        console.log(err)
      })
  }
  //查询基础信息
  GetUserInfo() {
    let _this = this
    _this.state.JudgeWhetherOrNotShowTable = [
      { ...JSON.parse(localStorage.getItem('userInfo')) },
    ]
    _this.userInfo = { ...JSON.parse(localStorage.getItem('userInfo')) }
  }
  getLinkURl(item) {
    let url = item.pointUrl != null ? item.pointUrl : item.url
    if (url.indexOf('MAG_PMIT') > -1) {
      //PMIT跳转
      let pwd = uncompileStr(localStorage.getItem('password'))
      let name = localStorage.getItem('userAccount')
      let penData = compileStr(
        JSON.stringify({
          password: pwd,
          remember: '0',
          username: name,
        })
      )
      window.open(
        getLinkToUrl('ipsa') + '/MAG_PMIT/new/#/?' + penData,
        '_blank'
      )
    } else if (url.indexOf('MAG_iHMS') > -1) {
      let pwd = localStorage.getItem('password')
      let name = localStorage.getItem('userAccount')
      item.url = item.url.replace('{name}', name)
      item.url = item.url.replace('{pwd}', pwd)
      window.open(getLinkToUrl('ipsa') + item.url)
    } else if (url.indexOf('MAG_SMARTSAFE') > -1) {
      //跳转至信息安全
      axios
        .get(
          getResponseUrl('ResponsePMITSystem') +
            '/rest/getIsmInfo/' +
            localStorage.getItem('userAccount')
        )
        .then((response) => {
          if (response.status === 200) {
            let roleId = response.data.data.role
            let username = encodeURIComponent(
              JSON.parse(localStorage.getItem('userInfo')).empName
            )
            let jobnumber = localStorage.getItem('empNo')
            let allPem =
              'userId=' +
              jobnumber +
              '&userName=' +
              username +
              '&roleId=' +
              roleId +
              '&password=' +
              localStorage.getItem('password') +
              '&userAccount=' +
              localStorage.getItem('userAccount')
            let codePem = encodeURIComponent(allPem)
            window.open(getLinkToUrl('ipsa') + url + '?' + codePem, '_blank')
          } else {
          }
        })
    } else if (url.indexOf('ICAN_SMARTSAFE') > -1) {
      //跳转至信息安全--RPC
      axios
        .get(
          getResponseUrl('ResponsePMITSystem') +
            '/rest/getIsmInfo/' +
            localStorage.getItem('userAccount')
        )
        .then((response) => {
          if (response.status === 200) {
            let roleId = response.data.data.role
            let username = encodeURIComponent(
              JSON.parse(localStorage.getItem('userInfo')).empName
            )
            let jobnumber = localStorage.getItem('empNo')
            let allPem =
              'userId=' +
              jobnumber +
              '&userName=' +
              username +
              '&roleId=' +
              roleId +
              '&password=' +
              localStorage.getItem('password') +
              '&userAccount=' +
              localStorage.getItem('userAccount')
            let codePem = encodeURIComponent(allPem)
            if (devProTest() === 'ipsa') {
              window.open(getLinkToUrl('ipsa') + url + '?' + codePem, '_blank')
            } else {
              window.open(
                'http://10.61.121.63:8080' + url + '?' + codePem,
                '_blank'
              )
            }
          } else {
          }
        })
    } else if (url.indexOf('MAGCOP') > -1) {
      let pwd = uncompileStr(localStorage.getItem('password'))
      let name = localStorage.getItem('userAccount')
      window.open(
        `${getLinkToUrl('ipsa')}${url}?userId=${name}&password=${compileStrCop(
          pwd
        )}`,
        '_blank'
      )
    } else {
      let menuId =
        item.pointId == -1 || item.pointId == undefined
          ? item.menuId
          : item.pointId //当前节点需要跳转页面的menuId
      let parentId =
        item.pointParentId == -1 || item.pointParentId == undefined
          ? item.parentId
          : item.pointParentId //当前节点需要跳转页面的parentId
      let realMenuId = item.menuId //点击当前节点的Id

      if (url.indexOf('MAG-ICAN') > -1) {
        //Ican自由工程
        let urls = url
        if (urls.indexOf('statistics/query') > -1) {
          let beginTime = moment()
            .startOf('day')
            .format('YYYY-MM-DD')
          let endTime = moment()
            .endOf('day')
            .format('YYYY-MM-DD')
          url = urls + `/${beginTime}/${endTime}`
        }
        if (devProTest() == 'develop') {
          window.location.href =
            frontUrlTest() +
            ':5002/#' +
            url +
            '/&menuId=' +
            menuId +
            '&parentId=' +
            parentId +
            '&systemId=' +
            item.systemId +
            '&realMenuId=' +
            realMenuId
        } else if (devProTest() == 'ipsa-test') {
          window.location.href =
            window.location.origin +
            '/iCan_Test/#' +
            url +
            '/&menuId=' +
            menuId +
            '&parentId=' +
            parentId +
            '&systemId=' +
            item.systemId +
            '&realMenuId=' +
            realMenuId
        } else if (devProTest() == '24') {
          window.location.href =
            window.location.origin +
            '/iCan/#' +
            url +
            '/&menuId=' +
            menuId +
            '&parentId=' +
            parentId +
            '&systemId=' +
            item.systemId +
            '&realMenuId=' +
            realMenuId
        } else if (devProTest() == 'ipsa') {
          window.location.href =
            window.location.origin +
            '/iCan/#' +
            url +
            '/&menuId=' +
            menuId +
            '&parentId=' +
            parentId +
            '&systemId=' +
            item.systemId +
            '&realMenuId=' +
            realMenuId
        }
      } else {
        //其他工程
        if (devProTest() === 'develop') {
          window.location.href =
            getLinkToUrl('platform') +
            url +
            '/&refreshToken=' +
            localStorage.getItem('refreshToken') +
            '&authToken=' +
            localStorage.getItem('authToken') +
            '&userAccount=' +
            localStorage.getItem('userAccount') +
            '&menuId=' +
            menuId +
            '&parentId=' +
            parentId +
            '&systemId=' +
            item.systemId +
            '&realMenuId=' +
            realMenuId
          //  window.open(getLinkToUrl('platform') + item + '/&refreshToken=' + localStorage.getItem("refreshToken") + "&authToken=" + localStorage.getItem("authToken") + '&userAccount=' + localStorage.getItem("userAccount"), '_blank');
        } else {
          window.location.href =
            getLinkToUrl('platform') +
            url +
            '/&menuId=' +
            menuId +
            '&parentId=' +
            parentId +
            '&systemId=' +
            item.systemId +
            '&realMenuId=' +
            realMenuId
          // window.open(getLinkToUrl('platform') + item, '_blank');
        }
      }
    }
  }
  setHeaderStyle() {
    let url = window.location.href
    let pathObj = getHeaderParams()
    let menuName = document.getElementsByClassName('menuName')
    if (menuName.length > 0) {
      ;[...menuName].forEach((item, index) => {
        let dataId = item.getAttribute('data-url')
        if (pathObj.systemId == dataId) {
          item.setAttribute(
            'style',
            'border-bottom: 3px solid #fff;font-weight: bold;padding: 0 4px;'
          )
        } else {
          item.removeAttribute('style')
        }
      })
    }
  }
  showMenu(arry, indexs) {
    arry.services.sort((a, b) => {
      return a.orderNum - b.orderNum
    })
    return (
      <Menu key={indexs}>
        {arry.services.map((Sonitem, index) => {
          return Sonitem.type === 0 ? ( //0 目录 1 菜单 2 资源项
            <SubMenu
              key={Sonitem.routeId}
              title={
                <span className="submenu-title-wrapper">{Sonitem.name}</span>
              }
            >
              {this.childrenMenu(Sonitem)}
            </SubMenu>
          ) : Sonitem.type === 1 ? (
            <Menu.Item key={Sonitem.routeId}>
              <span onClick={() => this.getLinkURl(Sonitem)}>
                {Sonitem.name}
              </span>
            </Menu.Item>
          ) : null
        })}
      </Menu>
    )
  }
  childrenMenu(Sonitem, index) {
    if (Sonitem.sonMenus != null && Sonitem.sonMenus.length > 0) {
      Sonitem.sonMenus.sort((a, b) => {
        return a.orderNum - b.orderNum
      })
      return Sonitem.sonMenus.map((children, index) => {
        if (children.type != 2) {
          let url = children.pointUrl != null ? children.pointUrl : children.url
          return (
            <Menu.Item key={index}>
              {url === '' || url == null ? (
                <span>{children.name}</span>
              ) : (
                <span onClick={() => this.getLinkURl(children)}>
                  {children.name}
                </span>
              )}
            </Menu.Item>
          )
        }
      })
    }
  }
  //帮助中心
  help() {
    window.open(this.props.url)
  }
  //个人中心
  linkPersonMsg() {
    window.open(
      getLinkToUrl('platform') +
        '/iCan/SBI/#/MAG-SBI/personalHome/' +
        this.state.JudgeWhetherOrNotShowTable[0].empNo
    )
  }
  // 注销
  CancleLogin() {
    //注销登录
    let _this = this
    let userAccount = localStorage.getItem('userAccount')
    dataAxios({
      url: 'https://ipsapro.isoftstone.com/iCan_Test/bk/logout',
      url: getAjaxurl() + '/logout',
      type: 'get',
      params: { userId: userAccount },
    }).then(function(response) {
      if (response.status === 200) {
        if (response.data.code === 200) {
          message.success('注销成功！', 0.6)
          window.localStorage.removeItem('refreshToken')
          window.localStorage.removeItem('authToken')
          window.localStorage.removeItem('empNo')
          window.localStorage.removeItem('userAccount')
          window.localStorage.removeItem('password')
          window.localStorage.removeItem('config')
          window.localStorage.removeItem('userInfo')
          window.localStorage.removeItem('Dictionary')
          window.localStorage.removeItem('subarea')
          window.localStorage.removeItem('statistics')
          window.localStorage.removeItem('userType')
          window.localStorage.removeItem('userInfoOpreate')
          window.sessionStorage.clear()
          window.localStorage.removeItem('deptList')
          window.location.href = getLinkToUrl('iCanLogin')
        } else {
        }
      }
    })
  }
  handleMenuClick = (e) => {
    this.setState({ roleName: e.key })
    // console.log('click', e);
  }
  render() {
    // const menu = (
    //     <Menu>
    //         <Menu.Item onClick={() => this.linkPersonMsg()}>个人中心</Menu.Item>
    //         <Menu.Item onClick={this.CancleLogin.bind(this)}>注销</Menu.Item>
    //     </Menu>
    // );
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        {this.state.roleList.length > 0
          ? this.state.roleList.map((item) => {
              return (
                <Menu.Item key={item.roleName}>
                  {/* <UserOutlined style={{ fontSize: "14px" }}></UserOutlined> */}
                  <span style={{ fontSize: '14px' }}>角色:</span>
                  <span style={{ fontSize: '14px', padding: '0 8px' }}>
                    {item.roleName}
                  </span>
                </Menu.Item>
              )
            })
          : null}
      </Menu>
    )
    return (
      <div>
        {this.state.JudgeWhetherOrNotShowTable.length > 0 ? (
          <div>
            <div className="HeaderClass">
              <div className="headerIpsa" style={{ float: 'left' }}>
                {/* logo */}
                <span
                  className="newLogo"
                  onClick={() => this.toLinkICan()}
                ></span>
                {//菜单
                this.state.MenuData.length > 0
                  ? this.state.MenuData.map((item, index) => {
                      return (
                        <Dropdown
                          key={item.systemId}
                          overlay={this.showMenu(item, item.systemId)}
                          overlayClassName="headerDropdown"
                          placement="bottomLeft"
                        >
                          <span className="menuName" data-url={item.systemId}>
                            {item.systemName}
                            {/* <Icon type='down' /> */}
                            <DownOutlined
                              style={{ marginLeft: 4 }}
                            ></DownOutlined>
                          </span>
                        </Dropdown>
                      )
                    })
                  : null}
              </div>

              <div
                className="headerRight"
                style={{ float: 'right', margin: '0 24px', marginTop: '16px' }}
              >
                {this.state.roleList.length > 0 && this.state.roleList ? (
                  <Dropdown
                    overlay={menu}
                    overlayClassName="roleDropdown"
                    trigger={['click']}
                  >
                    <span
                      title={'角色：' + this.state.roleName}
                      className="userHeader"
                      style={{ cursor: 'pointer' }}
                    ></span>
                  </Dropdown>
                ) : (
                  <span className="userHeader"></span>
                )}

                {this.state.JudgeWhetherOrNotShowTable.length > 0 ? (
                  <div className="userHeaderName">
                    <span
                      style={{
                        float: 'left',
                        width: '100%',
                        textAlign: 'center',
                      }}
                    >
                      {this.state.JudgeWhetherOrNotShowTable[0].empName}
                    </span>
                    <br></br>
                    <span style={{ width: '100%', textAlign: 'center' }}>
                      {this.state.JudgeWhetherOrNotShowTable[0].empNo}
                    </span>
                  </div>
                ) : null}

                {/* <span className='settingSvg' title="设置"></span> */}

                <span
                  style={{
                    color: '#fff',
                    position: 'relative',
                    top: '-10px',
                    margin: '0 12px',
                    cursor: 'pointer',
                  }}
                  onClick={this.CancleLogin.bind(this)}
                >
                  注销
                </span>
                {/* <Dropdown overlay={menu} trigger={["click"]}>
                                    <span className='personSvg' title="个人中心"></span>
                                </Dropdown> */}
                {this.props.url && this.props.url != '' ? (
                  <span
                    className="helpSvg"
                    title="帮助中心"
                    onClick={this.help.bind(this)}
                  ></span>
                ) : null}
              </div>
              <div style={{ clear: 'both' }}></div>
            </div>
            {/* 面包屑 */}
            {this.state.Breadcrumb && this.state.Breadcrumb.length > 0 ? (
              <Breadcrumb style={{ padding: '12px 24px' }}>
                {
                  // console.log(this.state.Breadcrumb)
                }
                {this.state.Breadcrumb.map((item, index) => {
                  return (
                    <Breadcrumb.Item key={index}>
                      {item.systemName ? (
                        <a
                          style={{ color: 'rgba(0,0,0,0.65)' }}
                          onClick={() => this.toLinkICan()}
                        >
                          {item.systemName}
                        </a>
                      ) : item.url && item.url != '' ? (
                        <a>{item.name}</a>
                      ) : (
                        <span style={{ color: 'rgba(0,0,0,0.25)' }}>
                          {item.name}
                        </span>
                      )}
                    </Breadcrumb.Item>
                  )
                })}
              </Breadcrumb>
            ) : null}
          </div>
        ) : null}
      </div>
    )
  }
}
export default HeaderMenu
